package com.ruoyi.analyse.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.common.utils.SecurityUtils;
import org.aspectj.weaver.patterns.TypePatternQuestions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.analyse.mapper.QuestionAnalysisMapper;
import com.ruoyi.analyse.domain.QuestionAnalysis;
import com.ruoyi.analyse.service.IQuestionAnalysisService;

/**
 * 问题分析Service业务层处理
 *
 * @author ruoyi
 */
@Service
public class QuestionAnalysisServiceImpl implements IQuestionAnalysisService
{
    @Autowired
    private QuestionAnalysisMapper questionAnalysisMapper;

    /**
     * 查询问题分析
     *
     * @param analysisId 问题分析主键
     * @return 问题分析
     */
    @Override
    public QuestionAnalysis selectQuestionAnalysisByAnalysisId(Long analysisId)
    {
        return questionAnalysisMapper.selectQuestionAnalysisByAnalysisId(analysisId);
    }

    /**
     * 查询问题分析列表
     *
     * @param questionAnalysis 问题分析
     * @return 问题分析
     */
    @Override
    public List<QuestionAnalysis> selectQuestionAnalysisList(QuestionAnalysis questionAnalysis)
    {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 如果不是管理员，则添加学院过滤条件
        if(!SecurityUtils.isAdmin(userId)){ // 或使用 SecurityUtils.isAdmin(loginUser.getUser().getUserId())
            questionAnalysis.setCollegeId(SecurityUtils.getLoginUser().getCollegeId());
        }
        return questionAnalysisMapper.selectQuestionAnalysisList(questionAnalysis);
    }

    /**
     * 新增问题分析
     *
     * @param questionAnalysis 问题分析
     * @return 结果
     */
    @Override
    public int insertQuestionAnalysis(QuestionAnalysis questionAnalysis)
    {
        // 设置学院ID
        if (questionAnalysis.getCollegeId() == null) {
            questionAnalysis.setCollegeId(SecurityUtils.getLoginUser().getCollegeId());
        }
        questionAnalysis.setCreateTime(new Date());
        return questionAnalysisMapper.insertQuestionAnalysis(questionAnalysis);
    }

    /**
     * 修改问题分析
     *
     * @param questionAnalysis 问题分析
     * @return 结果
     */
    @Override
    public int updateQuestionAnalysis(QuestionAnalysis questionAnalysis)
    {
        questionAnalysis.setUpdateTime(new Date());
        return questionAnalysisMapper.updateQuestionAnalysis(questionAnalysis);
    }

    /**
     * 批量删除问题分析
     *
     * @param analysisIds 需要删除的问题分析主键
     * @return 结果
     */
    @Override
    public int deleteQuestionAnalysisByAnalysisIds(Long[] analysisIds)
    {
        return questionAnalysisMapper.deleteQuestionAnalysisByAnalysisIds(analysisIds);
    }

    /**
     * 删除问题分析信息
     *
     * @param analysisId 问题分析主键
     * @return 结果
     */
    @Override
    public int deleteQuestionAnalysisByAnalysisId(Long analysisId)
    {
        return questionAnalysisMapper.deleteQuestionAnalysisByAnalysisId(analysisId);
    }

    /**
     * 分析问题内容并更新统计
     *
     * @param content 问题内容
     * @param userName 用户名
     * @return 分析结果
     */
    @Override
    public Map<String, Object> analyzeQuestion(String content, String userName)
    {
        Map<String, Object> result = new HashMap<>();

        // 1. 提取关键词
        List<String> keywords = extractKeywords(content);

        // 2. 识别学科分类
        String subject = identifySubject(content);

        // 3. 评估问题复杂度
        String complexity = evaluateComplexity(content);

        // 4. 识别问题类型
        String questionType = identifyQuestionType(content);

        // 5. 更新问题分析统计
        for (String keyword : keywords) {
            updateKeywordStatistics(keyword, subject, questionType, complexity);
        }

        // 6. 构建返回结果
        result.put("keywords", keywords);
        result.put("subject", subject);
        result.put("complexity", complexity);
        result.put("questionType", questionType);

        return result;
    }

    /**
     * 获取热门关键词列表
     *
     * @param limit 限制数量
     * @return 热门关键词列表
     */
    @Override
    public List<QuestionAnalysis> getTopKeywords(int limit, Long classId)
    {
        return questionAnalysisMapper.selectTopKeywords(limit, classId);
    }

    /**
     * 按学科统计问题数量
     *
     * @return 学科统计
     */
    @Override
    public List<Map<String, Object>> getSubjectStatistics(Long classId)
    {
        List<QuestionAnalysis> subjectList = questionAnalysisMapper.countQuestionsBySubject(classId);
        List<Map<String, Object>> result = new ArrayList<>();

        for (QuestionAnalysis qa : subjectList) {
            Map<String, Object> map = new HashMap<>();
            map.put("subject", qa.getSubject());
            map.put("count", qa.getFrequency());
            result.add(map);
        }

        return result;
    }

    /**
     * 获取按复杂度分类的问题统计
     *
     * @return 复杂度统计
     */
    @Override
    public Map<String, Integer> getComplexityStatistics(Long classId)
    {
        Map<String, Integer> result = new HashMap<>();
        int simpleCount = 0;
        int mediumCount = 0;
        int complexCount = 0;

        QuestionAnalysis query = new QuestionAnalysis();

        // 简单问题
        query.setComplexity("SIMPLE");
        query.setClassId(classId);
        List<QuestionAnalysis> simpleList = questionAnalysisMapper.selectQuestionAnalysisList(query);
        for (QuestionAnalysis qa : simpleList) {
            simpleCount += qa.getFrequency();
        }

        // 中等问题
        query.setComplexity("MEDIUM");
        query.setClassId(classId);
        List<QuestionAnalysis> mediumList = questionAnalysisMapper.selectQuestionAnalysisList(query);
        for (QuestionAnalysis qa : mediumList) {
            mediumCount += qa.getFrequency();
        }

        // 复杂问题
        query.setComplexity("COMPLEX");
        query.setClassId(classId);
        List<QuestionAnalysis> complexList = questionAnalysisMapper.selectQuestionAnalysisList(query);
        for (QuestionAnalysis qa : complexList) {
            complexCount += qa.getFrequency();
        }

        result.put("simple", simpleCount);
        result.put("medium", mediumCount);
        result.put("complex", complexCount);

        return result;
    }

    /**
     * 提取关键词
     *
     * @param content 内容
     * @return 关键词列表
     */
    private List<String> extractKeywords(String content) {
        List<String> keywords = new ArrayList<>();

        // 计算机专业关键词词库 - 实际应用中可以从配置文件或数据库加载
        String[] techKeywords = {
            "Java", "Python", "C\\+\\+", "数据结构", "算法", "数据库", "SQL", "操作系统",
            "网络", "编程", "开发", "框架", "前端", "后端", "web", "人工智能", "机器学习",
            "深度学习", "计算机网络", "网络安全", "软件工程", "代码", "bug", "调试", "测试",
            "运行", "编译", "系统", "架构", "设计模式", "API", "接口", "类", "对象", "函数",
            "方法", "变量", "Spring", "SpringBoot", "Vue", "React", "Angular", "数据分析",
            "大数据", "云计算", "微服务", "容器", "Docker", "Linux", "Windows", "服务器"
        };

        // 使用正则表达式匹配关键词
        for (String keyword : techKeywords) {
            Pattern pattern = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                keywords.add(keyword);
            }
        }

        // 如果没有匹配到关键词,取前5个字作为关键词
        if (keywords.isEmpty() && content.length() > 5) {
            keywords.add(content.substring(0, Math.min(5, content.length())));
        }

        return keywords;
    }

    /**
     * 识别学科分类
     *
     * @param content 内容
     * @return 学科分类
     */
    private String identifySubject(String content) {
        // 学科关键词映射 - 可以从配置或数据库加载
        Map<String, String> subjectKeywords = new HashMap<>();
        subjectKeywords.put("数据结构", "数据结构与算法");
        subjectKeywords.put("算法", "数据结构与算法");
        subjectKeywords.put("链表", "数据结构与算法");
        subjectKeywords.put("树", "数据结构与算法");
        subjectKeywords.put("图", "数据结构与算法");
        subjectKeywords.put("排序", "数据结构与算法");

        subjectKeywords.put("Java", "编程语言");
        subjectKeywords.put("Python", "编程语言");
        subjectKeywords.put("C++", "编程语言");
        subjectKeywords.put("JavaScript", "编程语言");
        subjectKeywords.put("变量", "编程语言");
        subjectKeywords.put("函数", "编程语言");

        subjectKeywords.put("数据库", "数据库系统");
        subjectKeywords.put("SQL", "数据库系统");
        subjectKeywords.put("MySQL", "数据库系统");
        subjectKeywords.put("Oracle", "数据库系统");
        subjectKeywords.put("表", "数据库系统");
        subjectKeywords.put("查询", "数据库系统");

        subjectKeywords.put("操作系统", "操作系统");
        subjectKeywords.put("Linux", "操作系统");
        subjectKeywords.put("Windows", "操作系统");
        subjectKeywords.put("进程", "操作系统");
        subjectKeywords.put("线程", "操作系统");
        subjectKeywords.put("内存", "操作系统");

        subjectKeywords.put("网络", "计算机网络");
        subjectKeywords.put("TCP", "计算机网络");
        subjectKeywords.put("IP", "计算机网络");
        subjectKeywords.put("HTTP", "计算机网络");
        subjectKeywords.put("协议", "计算机网络");

        subjectKeywords.put("前端", "Web开发");
        subjectKeywords.put("HTML", "Web开发");
        subjectKeywords.put("CSS", "Web开发");
        subjectKeywords.put("Javascript", "Web开发");
        subjectKeywords.put("Vue", "Web开发");
        subjectKeywords.put("React", "Web开发");

        subjectKeywords.put("后端", "系统开发");
        subjectKeywords.put("框架", "系统开发");
        subjectKeywords.put("Spring", "系统开发");
        subjectKeywords.put("SpringBoot", "系统开发");
        subjectKeywords.put("接口", "系统开发");
        subjectKeywords.put("API", "系统开发");

        subjectKeywords.put("人工智能", "人工智能");
        subjectKeywords.put("机器学习", "人工智能");
        subjectKeywords.put("深度学习", "人工智能");
        subjectKeywords.put("神经网络", "人工智能");

        subjectKeywords.put("软件工程", "软件工程");
        subjectKeywords.put("设计模式", "软件工程");
        subjectKeywords.put("测试", "软件工程");
        subjectKeywords.put("项目管理", "软件工程");

        // 默认学科
        String subject = "其他";

        // 判断内容中是否包含学科关键词
        for (Map.Entry<String, String> entry : subjectKeywords.entrySet()) {
            if (content.toLowerCase().contains(entry.getKey().toLowerCase())) {
                subject = entry.getValue();
                break;
            }
        }

        return subject;
    }

    /**
     * 评估问题复杂度
     *
     * @param content 内容
     * @return 复杂度评级
     */
    private String evaluateComplexity(String content) {
        // 简单规则: 问题长度 + 特定关键词判断
        int length = content.length();
        boolean hasComplexTerms = content.matches(".*(如何|为什么|原理|实现|设计|比较|分析).*");
        boolean hasCodeRequest = content.matches(".*(代码|编程|程序|实现|写一个).*");

        if (length > 100 || (length > 50 && hasComplexTerms) || (hasCodeRequest && hasComplexTerms)) {
            return "COMPLEX";
        } else if (length > 30 || hasComplexTerms || hasCodeRequest) {
            return "MEDIUM";
        } else {
            return "SIMPLE";
        }
    }

    /**
     * 识别问题类型
     *
     * @param content 内容
     * @return 问题类型
     */
    private String identifyQuestionType(String content) {
        if (content.matches(".*(什么是|概念|定义|介绍).*")) {
            return "概念解释";
        } else if (content.matches(".*(如何|怎么|怎样|步骤|方法).*")) {
            return "操作指导";
        } else if (content.matches(".*(为什么|原因|解释|分析).*")) {
            return "原理分析";
        } else if (content.matches(".*(区别|比较|不同).*")) {
            return "比较分析";
        } else if (content.matches(".*(代码|程序|编写|实现).*")) {
            return "代码实现";
        } else if (content.matches(".*(错误|问题|bug|异常|失败).*")) {
            return "错误诊断";
        } else if (content.matches(".*(优化|提高|改进).*")) {
            return "优化建议";
        } else {
            return "一般提问";
        }
    }

    /**
     * 更新关键词统计
     */
    private void updateKeywordStatistics(String keyword, String subject, String questionType, String complexity) {
        QuestionAnalysis qa = questionAnalysisMapper.selectQuestionAnalysisByKeywordAndSubject(keyword, subject);

        if (qa != null) {
            // 更新已有记录
            qa.setFrequency(qa.getFrequency() + 1);
            qa.setUpdateTime(new Date());
            questionAnalysisMapper.updateQuestionAnalysis(qa);
        } else {
            // 创建新记录
            qa = new QuestionAnalysis();
            qa.setKeyword(keyword);
            qa.setSubject(subject);
            qa.setQuestionType(questionType);
            qa.setComplexity(complexity);
            qa.setFrequency(1);
            qa.setCreateTime(new Date());
            qa.setUpdateTime(new Date());
            questionAnalysisMapper.insertQuestionAnalysis(qa);
        }
    }

    /**
     * 根据关键词和学科查询问题分析
     *
     * @param keyword 关键词
     * @param subject 学科
     * @return 问题分析
     */
    @Override
    public QuestionAnalysis selectQuestionAnalysisByKeywordAndSubject(String keyword, String subject) {
        return questionAnalysisMapper.selectQuestionAnalysisByKeywordAndSubject(keyword, subject);
    }

    /**
     * 获取问题类型统计
     * @return 问题类型及其数量的映射
     */
    @Override
    public Map<String, Integer> getQuestionTypeStatistics(Long classId) {
        Map<String, Integer> result = new HashMap<>();

        // 获取所有不同的问题类型
        List<String> questionTypes = questionAnalysisMapper.selectDistinctQuestionTypes(classId);

        // 如果没有实现上述方法，则使用预定义的问题类型列表
        if (questionTypes == null || questionTypes.isEmpty()) {
            questionTypes = new ArrayList<>();
            questionTypes.add("概念解释");
            questionTypes.add("操作指导");
            questionTypes.add("原理分析");
            questionTypes.add("比较分析");
            questionTypes.add("代码实现");
            questionTypes.add("错误诊断");
            questionTypes.add("优化建议");
            questionTypes.add("一般提问");
        }

        // 统计每种问题类型的数量
        for (String questionType : questionTypes) {
            QuestionAnalysis query = new QuestionAnalysis();
            query.setQuestionType(questionType);
            query.setClassId(classId);
            List<QuestionAnalysis> typeList = questionAnalysisMapper.selectQuestionAnalysisList(query);

            int count = 0;
            for (QuestionAnalysis qa : typeList) {
                count += qa.getFrequency();
            }

            result.put(questionType, count);
        }

        return result;
    }



}
